package com.lw.leetcode.other.c;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * 6264. 让数组不相等的最小总代价
 *
 * @author liw
 * @version 1.0
 * @date 2022/12/11 12:49
 */
public class MinimumTotalCost {

    public long minimumTotalCost(int[] nums1, int[] nums2) {
        List<Integer> values = new ArrayList<>();
        long sum = 0;
        int length = nums1.length;
        for (int i = 0; i < length; i++) {
            if (nums1[i] == nums2[i]) {
                values.add(nums1[i]);
                sum += i;
            }
        }
        int v = 0;
        int c = 0;
        int size = values.size();
        for (Integer value : values) {
            if (c == 0) {
                v = value;
                c = 1;
                continue;
            }
            if (value == v) {
                c++;
            } else {
                c--;
            }
        }
        if (c == 0) {
            return sum;
        }
        c = 0;
        for (Integer value : values) {
            if (value == v) {
                c++;
            }
        }
        c <<= 1;
        if (c <= size) {
            return sum;
        }
        c -= size;
        for (int i = 0; i < length; i++) {
            if (nums1[i] != nums2[i] && nums1[i] != v && nums2[i] != v) {
                sum += i;
                c--;
                if (c == 0) {
                    return sum;
                }
            }
        }
        return -1;
    }
}
